package com.difsonapps.contacttranslator.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.difsonapps.contacttranslator.dto.UserDTO;




@Repository
@Transactional
public class UserDAO {

	@Autowired
	protected SessionFactory sessionFactory;

	@Transactional
	public void insert(UserDTO userDTO) {
		sessionFactory.getCurrentSession().save(userDTO);
	}

	@Transactional
	public void update(UserDTO userDTO) {
		sessionFactory.getCurrentSession().update(userDTO);
	}

	@Transactional
	public UserDTO get(int id) {
		return (UserDTO) sessionFactory.getCurrentSession().get(UserDTO.class,
				id);
	}

	@Transactional
	public UserDTO getByEmail(String email) {
		
		return  (UserDTO) sessionFactory.getCurrentSession()
				.createQuery("Select u from UserDTO u where u.email=:email")
				.setParameter("email", email).uniqueResult();
		
	}
	@Transactional
	public UserDTO getByCode(String code) {
		
		return  (UserDTO) sessionFactory.getCurrentSession()
				.createQuery("Select u from UserDTO u where u.code=:code")
				.setParameter("code", code).uniqueResult();
		
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<UserDTO> getAll() {
		return (List<UserDTO>) sessionFactory.getCurrentSession()
				.createQuery("Select u from UserDTO u").list();
	}

	@Transactional
	public void delete(UserDTO userDTO) {
		sessionFactory.getCurrentSession().delete(userDTO);
	}

	@Transactional
	public int deleteByEmail(String email) {
		return sessionFactory.getCurrentSession()
				.createQuery("Delete from UserDTO u where u.email=:email")
				.setParameter("email", email).executeUpdate();
	}
	
	@Transactional
	public UserDTO getByEmailCode(String code,String email) {
		return  (UserDTO) sessionFactory.getCurrentSession()
				.createQuery("Select u from UserDTO u where u.code=:code and u.email=:email")
				.setParameter("code", code)
				.setParameter("email", email).uniqueResult();
	}
	
	
	@Transactional
	public UserDTO getByNumber(String phone) {
		return  (UserDTO) sessionFactory.getCurrentSession()
				.createQuery("Select u from UserDTO u where u.phone=:phone")
				.setParameter("phone", phone).uniqueResult();
	}

}
